package com.hula.onion.book.server.spider.platforms.xiaoniuzaixian;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.JedisUtils;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.config.SysConstants;
import com.hula.onion.book.server.model.AccountInfo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:49
 *
 * @author shan
 * @version 1.0
 */
@Component
public class XiaoNiuZaiXianSpiderHelper {

    /**
     * 组装请求参数
     *
     * @param form
     * @return
     */
    public Map<String, Object> installRequestParams(LoginForm form) throws Exception {

        Map<String, Object> map = new HashMap<>(3);

        map.put("username", form.getUserName());
        map.put("password", form.getPassword());
        map.put("code", form.getTicket());

        String nameKey = SysConstants.REDIS_KEY_PRE + SysConstants.INDEX_PAGE_INFO_PRE + SysConstants.TOKEN_NAME + form.getPlatformId() + ":" + form.getUserId();
        String valueKey = SysConstants.REDIS_KEY_PRE + SysConstants.INDEX_PAGE_INFO_PRE + SysConstants.TOKEN_VALUE + form.getPlatformId() + ":" + form.getUserId();

        map.put("ooh.token.name", JedisUtils.getInstance().get(nameKey));
        map.put("ooh.token.value", JedisUtils.getInstance().get(valueKey));

        return map;

    }

    /**
     * 解析账户余额
     *
     * @param html
     * @return
     */
    public CommonResponse parseAccountBalance(String html) {

        try {
            AccountInfo accountInfo = new AccountInfo();

            Document dc = Jsoup.parse(html);
            //总余额
            Element element = dc.selectFirst("tr.total");
            String result = element.children().get(1).children().get(0).text();
            accountInfo.setAmount(new BigDecimal(result));
            //代收收益
            element = dc.selectFirst("table");
            Elements trs = element.select("tr");
            String waitInterest = trs.get(3).select("td").get(2).text();
            String wFinal = StringUtils.remove(waitInterest, " 元");
            accountInfo.setWaitIntrest(new BigDecimal(wFinal));
            //总收益
            String totalInterest = dc.selectFirst("div.cont-po").children()
                    .get(1).text();
            String tFinal = StringUtils.remove(totalInterest, " 元");
            accountInfo.setTotalIntrest(new BigDecimal(tFinal));
            return new CommonResponse(accountInfo);
        } catch (Exception e) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
    }
}
